#!/usr/bin/env python
# -*- coding: utf-8 -*-
from functools import reduce
from operator import add

# sum的最常见用法计算一个序列的累加和
print (sum([1,2,3]))
# 6
# # sum 函数原型是 sum(iterable, start), 还可以给个初始值
print(sum([1, 2, 3], 10))
# 16


# 另外一个比较Hack一些的用法, 展开2层的嵌套列表
iterable = [[1, 2], [3, 4], [5, 6], [7, 8]]
start = [0]
print(sum(iterable, start))
# [0, 1, 2, 3, 4, 5, 6, 7, 8]


# sum函数是和下面的过程是等效的
for element in iterable:
    start += element
print(start)
# [0, 1, 2, 3, 4, 5, 6, 7, 8]


# 实际上sum可以看成reduce()的特殊情况

start = []
print(reduce(add, iterable, start))
# [1, 2, 3, 4, 5, 6, 7, 8]